/**
 * @description  券池审批
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, Select, TreeSelect, message } from 'antd';
import { SelectC, TreeSelectC, InputNumberC } from '../../../../comps';
import style from './index.less';
import moment from 'moment';
import uuid from 'es6-uuid';
import RowForm3 from './rowForm3';
const FormItem = Form.Item;
const { Option } = Select;

@Form.create()
class RowForm2 extends PureComponent {
  constructor() {
    super();

    this.state = {
      value: undefined,
      isChange: false,
      title2: [],
      isFlag: false,
      timeOutGap: 500,
      effectType: 1,
      rowData: [],
      rowData2: [],
      symbol: [],
      contentType: 1, // 内容类型 1-输入框 2-下拉框 3-树形多选框 4-日期选择框
      contentData: [],
      tag: 1, //内容下拉数据形式 1-发行主体  2-其他
      isMultiple: false, //内容下拉是否支持多选
      defaultData: [],
      formItemLayout: {
        labelCol: {
          span: 0,
        },
        wrapperCol: {
          span: 24,
        },
      },
      newEffectiveTime: true,
      units: undefined, //根据不同的维度展示不同的单位
      unitPerCent: [
        'valuation_rate_of_return',
        'yield_in_the_past_month',
        'yield_in_recent_three_months',
        'yield_in_the_past_six_months',
        'yearly_one_year_yield',
        'yield_since_establishment',
      ], //单位是百分号的维度
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    const { type, selectData, defaultData } = this.props;
    const { unitPerCent } = this.state;
    if (type !== 'add') {
      defaultData.content = defaultData.content && defaultData.content.split(',');
      if (unitPerCent.some((i) => i == defaultData.dimension)) {
        defaultData.content = +defaultData.content[0] * 100;
      }
      if (defaultData.dimension == 'fund_size') {
        //基金规模，单位亿元
        defaultData.content = +defaultData.content[0] / 100000000;
      }
      if (defaultData.dimension == 'circulation_market_value') {
        //流通市值，单位万元
        defaultData.content = +defaultData.content[0] / 10000;
      }
      if (!defaultData.effectiveTime) {
        this.setState({
          newEffectiveTime: false,
        });
      }
      this.dimensionOnChange(defaultData.dimension);
      this.setState({
        symbol: selectData.flow_filter_operation_symbol,
        defaultData: defaultData,
      });
    }
    if (defaultData && defaultData.effect == 2) {
      defaultData.autoItem.shift();
      this.setState({
        effectType: 2,
        rowData2: defaultData.autoItem,
      });
    }
  }

  // 新增行
  addRow = () => {
    const { type } = this.props;
    let rowData = this.state.rowData || [];
    let rowData2 = this.state.rowData2 || [];
    if (this.state.rowData.length > 2) {
      message.info('最多添加三个子条目');
      return;
    }
    if (type == 'add') {
      rowData.push({ rowId: uuid(32) });
      this.setState({
        rowData: [...rowData],
      });
    } else {
      rowData2.push({ id: uuid(32) });
      this.setState({
        rowData2: [...rowData2],
      });
    }
  };

  // 删除子条目
  delOneRow = (e) => {
    const { type } = this.props;
    let newDate = type == 'add' ? this.state.rowData.filter((item) => item.rowId != e) : this.state.rowData2.filter((item) => item.id != e);
    if (type == 'add') {
      this.setState({
        rowData: newDate,
        isError: false,
      });
    } else {
      this.setState({
        rowData2: newDate,
        isError: false,
      });
    }
  };

  // 删除行
  delete = () => {
    this.props.onDelete(this.props.rowId);
  };

  // 获取数据
  getData2 = () => {
    const {
      form: { validateFields },
      defaultData,
      type,
    } = this.props;
    const { rowData, rowData2, contentType, unitPerCent } = this.state;
    let data = {}; //条目数据
    let resArr = []; //子条目数据
    let dimensionArr = []; //维度数据
    let symbolArr = []; //符号数据
    let uniqueDimensionArr = []; //去重后维度数据
    let uniqueSymbolArr = []; //去重后符号数据
    let arr = {};
    validateFields((err, fieldsValue) => {
      if (!err) {
        data = fieldsValue;

        if (contentType == 4) {
          data.content = fieldsValue.content.format('YYYY-MM-DD');
        }
        if (Array.isArray(fieldsValue.content)) {
          data.content = fieldsValue.content.join(',');
        }
        if (unitPerCent.some((i) => i == fieldsValue.dimension)) {
          data.content = fieldsValue.content / 100;
        }
        if (fieldsValue.dimension == 'fund_size') {
          //基金规模，单位亿元
          data.content = fieldsValue.content * 100000000;
        }
        if (fieldsValue.dimension == 'circulation_market_value') {
          //流通市值，单位万元
          data.content = fieldsValue.content * 10000;
        }
        delete data.tags;
      }
    });
    if (this.state.isChange) {
      data.tags = this.state.title2;
    } else {
      data.tags = defaultData && defaultData.tags ? defaultData.tags : [];
    }
    if (type == 'add') {
      for (let i in rowData) {
        const datas = rowData[i].ref.getData3();
        if (JSON.stringify(datas) == '{}') {
          //有未填写的子条目时给出错误提示
          this.props.isError3OnChange(true);
          return;
        }
        resArr.push(datas);
      }
      this.props.isError3OnChange(false);
    } else {
      for (let i in rowData2) {
        const datas = rowData2[i].ref.getData3();
        if (JSON.stringify(datas) == '{}') {
          //有未填写的子条目时给出错误提示
          this.props.isError3OnChange(true);
          return;
        }
        resArr.push(datas);
      }
      this.props.isError3OnChange(false);
    }
    //判断维度和符号是否重复
    dimensionArr.push(data.dimension + data.symbol);
    resArr.map((item) => {
      dimensionArr.push(item.dimension + item.symbol);
    });
    uniqueDimensionArr = this.unique(dimensionArr);
    uniqueSymbolArr = this.unique(symbolArr);
    if (dimensionArr.length != uniqueDimensionArr.length) {
      message.error('条目维度和符号不能重复');
      return;
    }
    (arr.content = data.content), (arr.dimension = data.dimension), (arr.symbol = data.symbol);
    data.autoItem = [];
    data.autoItem = resArr;
    data.autoItem.unshift(arr);
    return data;
  };

  // 数组去重
  unique = (arr) => {
    return [...new Set(arr)];
  };

  // 点击子节点获取父节点
  showwwww = (value, node, extra) => {
    const tagArr = _.cloneDeep(extra.selectedNodes);
    console.log(tagArr, 'zht');
    const newArr = [];
    if (tagArr && tagArr.length) {
      tagArr.map((item) => {
        newArr.push(item.props);
      });
    }
    const newArr2 = _.cloneDeep(newArr);
    const newTag = [];
    if (newArr2.length) {
      newArr2.map((item) => {
        newTag.push(item.value);
        if (item.pid !== null) {
          newTag.push(item.pid);
        }
      });
    }
    const newTag2 = this.unique(newTag);
    this.setState({
      title2: newTag2,
      isChange: true,
    });
  };

  // 内容
  changeContent = (value) => {
    const { timeOutGap } = this.state;
    const { dispatch } = this.props;
    if (value) {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        dispatch({
          type: 'couponPoolApprovalM/searchContent',
          payload: {
            value: value,
          },
        });
      }, timeOutGap);
    }
  };

  // 响应生效方式点击
  effect = (e) => {
    this.setState({ effectType: e, rowData: [], rowData2: [] });
  };

  changeTreeData = (arr) => {
    let tempArr = [];
    arr.forEach((item) => {
      tempArr.push({
        value: item.code,
        title: item.value,
        selectable: !item.children?.length,
        children: this.changeTreeData(item.children || []),
      });
    });
    return tempArr;
  };

  // 响应维度点击
  dimensionOnChange = (e) => {
    const {
      form: { resetFields },
      globalM: {
        dataDictionary: { CREDITBND_MONITOR_BONDTYPEI = [] },
      },
      couponPoolApprovalM: { symbolData1, symbolData2 },
      poolType,
      selectData,
      dispatch,
    } = this.props;
    const bondTypeList = this.changeTreeData(CREDITBND_MONITOR_BONDTYPEI);
    resetFields(['content', 'symbol']);
    if (poolType == 'bond') {
      //债券
      if (e == 'bond_type') {
        // 债券类型
        this.setState({
          symbol: symbolData1,
          contentData: bondTypeList,
          contentType: 3,
          isMultiple: true,
        });
      } else if (e == 'issuer') {
        // 发行主体
        this.setState({
          symbol: symbolData2,
          tag: 1,
          contentType: 2,
          isMultiple: true,
        });
      } else if (e == 'subject_rating' || e == 'debt_rating') {
        //主体评级、债项评级
        let newData = [];
        selectData.RATERANGESTART_END.map((item) => {
          newData.push({ title: item.value, value: item.code });
        });
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentData: newData,
          tag: 2,
          contentType: 2,
          isMultiple: false,
        });
      } else {
        if (e == 'remaining_period') {
          //剩余期限
          this.setState({ units: 'Y' });
        } else if (e == 'valuation_rate_of_return') {
          this.setState({ units: '%' });
        } else {
          this.setState({ units: '元' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    } else if (poolType == 'fund') {
      //基金
      if (e == 'fund_type') {
        //基金类型
        let newData = [];
        selectData.fund_Trade_FundStatus.map((item) => {
          newData.push({ title: item.value, value: item.code });
        });
        this.setState({
          symbol: symbolData1,
          contentData: newData,
          tag: 2,
          contentType: 2,
          isMultiple: true,
        });
      } else if (e == 'startdate') {
        //成立日期，内容为日期选择框
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 4,
        });
      } else {
        if (e == 'fund_size') {
          this.setState({ units: '亿' });
        } else {
          this.setState({ units: '%' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    } else {
      //股票
      if (e == 'FINDUCODE_SW') {
        //申万一级
        this.setState({ symbol: symbolData1 });
        dispatch({
          type: 'couponPoolApprovalM/searchContentOne',
          payload: {},
          callback: (data) => {
            if (data) {
              this.setState({
                contentData: data,
                tag: 2,
                contentType: 2,
                isMultiple: true,
              });
            }
          },
        });
      } else if (e == 'SINDUCODE_SW') {
        //申万二级
        this.setState({ symbol: symbolData1 });
        dispatch({
          type: 'couponPoolApprovalM/searchContentTwo',
          payload: {},
          callback: (data) => {
            if (data) {
              this.setState({
                contentData: data,
                tag: 2,
                contentType: 2,
                isMultiple: true,
              });
            }
          },
        });
      } else {
        if (e == 'circulation_market_value') {
          this.setState({ units: '万' });
        } else if (e == 'P/B_ratio' || e == 'P/E_ratio') {
          this.setState({ units: undefined });
        } else {
          this.setState({ units: '元' });
        }
        this.setState({
          symbol: selectData.flow_filter_operation_symbol,
          contentType: 1,
        });
      }
    }
  };

  // 渲染查询表单
  formRender = () => {
    const {
      form: { getFieldDecorator },
      type,
      colsNum,
      isDisabled,
      tagData,
      selectData,
      poolType,
      couponPoolApprovalM: { issuer },
    } = this.props;
    const { rowData, rowData2, symbol, tag, contentType, isMultiple, contentData, defaultData, formItemLayout, newEffectiveTime, units } = this.state;
    const tags = poolType == 'bond' ? tagData.bondTag : poolType == 'fund' ? tagData.fundTag : tagData.stockTag;
    const dimension =
      poolType == 'bond' ? selectData.flow_filter_dimension_bond : poolType == 'fund' ? selectData.flow_filter_dimension_fund : selectData.flow_filter_dimension_stock;
    const flexData = [
      { code: '1', id: '1', value: '单一' },
      { code: '2', id: '2', value: '联合' },
    ];
    // 计算每列宽度
    const styleRow = {};
    if (colsNum) {
      const width = parseFloat(95 / (colsNum - 1)) + '%';
      styleRow.width = width;
      styleRow.paddingRight = '10px';
    }
    return (
      <div className={style.formStyle}>
        <div style={{ display: 'flex' }}>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`effect`, {
                initialValue: type !== 'add' ? defaultData.effect : '',
                rules: [{ required: true, message: ` ` }],
              })(
                <Select style={{ width: '100%' }} disabled={type == 'see' ? true : false} onChange={this.effect}>
                  {flexData
                    ? flexData.map((item) => {
                        return (
                          <Option key={item.id} value={item.code}>
                            {item.value}
                          </Option>
                        );
                      })
                    : null}
                </Select>,
              )}
            </FormItem>
          </div>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`dimension`, {
                initialValue: type !== 'add' ? defaultData.dimension : '',
                rules: [{ required: true, message: ` ` }],
              })(
                <Select style={{ width: '100%' }} disabled={type == 'see' ? true : false} onChange={this.dimensionOnChange}>
                  {dimension
                    ? dimension.map((item) => {
                        return (
                          <Option key={item.id} value={item.code}>
                            {item.value}
                          </Option>
                        );
                      })
                    : null}
                </Select>,
              )}
            </FormItem>
          </div>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`symbol`, {
                initialValue: type !== 'add' ? defaultData.symbol : '',
                rules: [{ required: true, message: ` ` }],
              })(
                <Select style={{ width: '100%' }} disabled={type == 'see' ? true : false}>
                  {symbol
                    ? symbol.map((item) => {
                        return (
                          <Option key={item.id} value={item.code}>
                            {item.value}
                          </Option>
                        );
                      })
                    : null}
                </Select>,
              )}
            </FormItem>
          </div>
          <div style={styleRow}>
            {contentType == 1 ? (
              <InputNumberC
                form={this.props.form}
                dataIndex={'content'}
                initialValue={type !== 'add' ? defaultData.content : null}
                disabled={type == 'see' ? true : false}
                formItemLayout={formItemLayout}
                rules={[{ required: true, message: '' }]}
                unit={units}
                precision={4}
              />
            ) : contentType == 3 ? (
              <TreeSelectC
                form={this.props.form}
                dataIndex={'content'}
                dataSource={contentData}
                formItemLayout={formItemLayout}
                rules={[{ required: true, message: '' }]}
                allowClear={true}
                isMultiple={true}
                treeDefaultExpandAll={true}
                disabled={type == 'see' ? true : false}
                initialValue={type !== 'add' ? defaultData.content : []}
                treeCheckable={true}
                showCheckedStrategy={'SHOW_CHILD'}
                maxTagCount={0}
              />
            ) : contentType == 4 ? (
              <FormItem>
                {getFieldDecorator(`content`, {
                  initialValue: type !== 'add' ? moment(defaultData.content[0]) : '',
                  rules: [{ required: true, message: ` ` }],
                })(<DatePicker style={{ width: '100%' }} disabled={type == 'see' ? true : false} />)}
              </FormItem>
            ) : tag == 1 ? (
              <FormItem>
                {getFieldDecorator(`content`, {
                  //支持模糊搜索下拉
                  initialValue: type !== 'add' ? defaultData.content : '',
                  rules: [{ required: true, message: ` ` }],
                })(
                  <Select style={{ width: '100%' }} filterOption={false} showSearch onSearch={this.changeContent} disabled={type == 'see' ? true : false}>
                    {issuer
                      ? issuer.map((item) => {
                          return (
                            <Option key={item} value={item}>
                              {item}
                            </Option>
                          );
                        })
                      : null}
                  </Select>,
                )}
              </FormItem> //多选下拉框
            ) : (
              <SelectC
                form={this.props.form}
                dataIndex={'content'}
                rules={[{ required: true, message: ' ' }]}
                allowClear={true}
                dataSource={contentData}
                isMultiple={isMultiple}
                disabled={type == 'see' ? true : false}
                initialValue={type !== 'add' ? defaultData.content : undefined}
                maxTagCount={0}
              />
            )}
          </div>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`effectiveTime`, {
                initialValue: type !== 'add' && newEffectiveTime ? moment(defaultData.effectiveTime) : '',
                rules: [{ required: true, message: ` ` }],
              })(<DatePicker style={{ width: '100%' }} disabled={type == 'see' ? true : false} />)}
            </FormItem>
          </div>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`expirationTime`, {
                initialValue: type !== 'add' && newEffectiveTime ? moment(defaultData.expirationTime) : '',
                rules: [{ required: true, message: ` ` }],
              })(<DatePicker style={{ width: '100%' }} disabled={type == 'see' ? true : false} />)}
            </FormItem>
          </div>
          <div style={styleRow}>
            <FormItem>
              {getFieldDecorator(`tags`, {
                initialValue: type !== 'add' ? defaultData.tags : [],
              })(
                <TreeSelect
                  treeData={tags}
                  placeholder='请选择标签'
                  allowClear
                  multiple={true}
                  treeDefaultExpandAll
                  maxTagCount={0}
                  onSelect={(value, node, extra) => this.showwwww(value, node, extra)}
                  onDeselect={(value, node, extra) => this.showwwww(value, node, extra)}
                  style={{ width: '100%' }}
                  disabled={isDisabled}
                />,
              )}
            </FormItem>
          </div>
          {type == 'see' ? null : (
            <div style={{ width: '45px', textAlign: 'center' }}>
              <a onClick={this.delete}>
                <MinusCircleOutlined />
              </a>
            </div>
          )}
        </div>
        {this.state.effectType == 2
          ? type == 'add'
            ? rowData && rowData.length
              ? rowData.map((item, index) => {
                  return (
                    <RowForm3
                      rowId={item.rowId}
                      key={item.rowId}
                      colsNum={colsNum}
                      selectData={selectData}
                      onDelete={this.delOneRow}
                      poolType={poolType}
                      type={type}
                      onRef={(ref) => {
                        item.ref = ref;
                      }}
                    />
                  );
                })
              : null
            : rowData2 && rowData2.length
            ? rowData2.map((item, index) => {
                return (
                  <RowForm3
                    rowId={item.id}
                    key={item.id}
                    colsNum={colsNum}
                    selectData={selectData}
                    defaultData={item}
                    onDelete={this.delOneRow}
                    poolType={poolType}
                    type={type}
                    onRef={(ref) => {
                      item.ref = ref;
                    }}
                  />
                );
              })
            : null
          : null}

        {this.state.effectType == 2 ? (
          type == 'see' ? null : (
            <div className='icon_s' style={{ marginLeft: '165px', marginTop: '10px' }}>
              <a onClick={this.addRow}>
                <PlusCircleOutlined />
              </a>
            </div>
          )
        ) : null}
      </div>
    );
  };
  render() {
    return <div className={style.modals}>{this.formRender()}</div>;
  }
}

export default connect(({ couponPoolApprovalM, globalM }) => ({
  couponPoolApprovalM,
  globalM,
}))(RowForm2);
